﻿using System;
using System.Web.Script.Services;
using System.Web.Services;
using System.Xml;
using Webapp;

namespace xundh.API.Tools
{
    /// <summary>
    /// PhoneLocation 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://www.lansezhongjie.com/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务，请取消注释以下行。 
    [System.Web.Script.Services.ScriptService]
    public class PhoneLocation : BaseService
    {

        [WebMethod(EnableSession = true)]
        [ScriptMethod(UseHttpGet = true)]
        public string Query(string phone)
        {
            return ReadFromApi(phone);
        }
        private string ReadFromApi(string phone)
        {
            string url = "http://life.tenpay.com/cgi-bin/mobile/MobileQueryAttribution.cgi?chgmobile=";
            try
            {
                //先从本地数据库里找
                xundh.API.Tools.Tools_MobileArea service = new xundh.API.Tools.Tools_MobileArea();
                xundh.Model.Tools_MobileArea m = service.Query(phone);
                if (m == null)
                {
                    //尝试从远程获取
                    XmlDocument element = StringUtil.getUrlXml(url + phone);
                    XmlElement root = element.DocumentElement;
                    XmlNode msg = root.SelectSingleNode("retmsg");
                    if (msg.InnerText == "error")
                    {
                        //获取失败
                        return "";
                    }
                    else
                    {
                        XmlNode province = root.SelectSingleNode("province");
                        XmlNode city = root.SelectSingleNode("city");
                        XmlNode supplier = root.SelectSingleNode("supplier");
                        string writecity = province.InnerText + "省" + city.InnerText + "市";
                        //写入本地数据库
                        string shortnumber = phone;
                        if (phone.Length > 7)
                            shortnumber = phone.Substring(0, 7);
                        service.Add(0, int.Parse(shortnumber), "", writecity, supplier.InnerText);
                        return writecity;
                    }
                }
                else
                    return m.city;

            }
            catch (Exception)
            {
                return "";
            }
        }
    }
}